<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\model;


use think\Model;


class AlibabaCloudToke extends Model
{
    
    protected $AccessKeyId = 'LTAI4FtUWnzVJMvT5mxSRh5k';//阿里云账号AccessKey ID
    protected $Action = 'CreateToken';//POP API名称：CreateToken
    protected $Version = '2019-02-28';//POP API版本：2019-02-28
    protected $Format = 'JSON';//响应返回的类型：JSON
    protected $RegionId = 'cn-shanghai';//服务所在的地域ID：cn-shanghai
    protected $SignatureMethod = 'HMAC-SHA1';//签名算法：HMAC-SHA1
    protected $SignatureVersion = '1.0';//签名算法版本：1.0
    

    function encodeText($text)
    {
        $encodedText = rawurlencode($text);
        return str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $encodedText);
    }
    
    function encodeDict($dic)
    {
        $keys = array_keys($dic);
        sort($keys);
        $dic_sorted = array();
        foreach ($keys as $key) {
            $dic_sorted[] = $key . '=' . urlencode($dic[$key]);
        }
        $encoded_text = implode('&', $dic_sorted);
        $encoded_text = str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $encoded_text);
        return $encoded_text;
     
    }
    
    function createToken()
    {
        $parameters = [
            'AccessKeyId' => $this->AccessKeyId,
            'Action' => 'CreateToken',
            'Format' => 'JSON',
            'RegionId' => 'cn-shanghai',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid(),
            'SignatureVersion' => '1.0',
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'Version' => '2019-02-28'
        ];
        
        // Construct canonicalized query string
        $queryString = $this->encodeDict($parameters);
        // Construct string to sign
        $stringToSign = 'GET&' . $this->encodeText('/') . '&' . $this->encodeText($queryString);
        // Calculate signature
        $secretedString = hash_hmac('sha1', $stringToSign, 'IGPGxXkIMHgSy2wexMyPkvTnP942Wj'. '&', true);
        $signature      = base64_encode($secretedString);
        // URL encode the signature
        $signature = $this->encodeText($signature);
      
        // Call the service
        $fullUrl = 'http://nls-meta.cn-shanghai.aliyuncs.com?Signature=' . $signature . '&' . $queryString;
        $data=send_post($fullUrl,[],2);
       
        // Send HTTP GET request
        $response =json_decode($data,true);
        if (!isset($response['code'])) {
            return ['code'=>200,'toke'=>$response['Token'],'message'=>'请求成功'];
        }
        return ['code'=>300,'toke'=>'','message'=>$response['Message']];
    }


    
    
}





